package com.example.demo60springsecurity27.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

import javax.annotation.Resource;

/**
 * 以前我们自定义类继承自 WebSecurityConfigurerAdapter 来配置我们的 SpringSecurity，我们主要是配置两个东西:
 * configure(HttpSecurity)
 * configure(WebSecurity)
 * <p>
 * 前者主要是配置 Spring Security 中的过滤器链，后者则主要是配置一些路径放行规则。
 * <p>
 * 现在在 WebSecurityConfigurerAdapter 的注释中，人家已经把意思说的很明白了:
 * 1.以后如果想要配置过滤器链，可以通过自定义 SecurityFilterChain Bean 来实现。
 * 2.以后如果想要配置 WebSecurity，可以通过 WebSecurityCustomizer Bean 来实现。
 */
@Configuration
public class SecurityConfig {

    @Bean
    PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

    // 自定义用户
    @Bean
    UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager us = new InMemoryUserDetailsManager();
        us.createUser(User.withUsername("wangnian").password("123").roles("admin").build());
        return us;
    }

    @Bean
    WebSecurityCustomizer webSecurityCustomizer() {
        return web -> web.ignoring().antMatchers("/hello");
    }

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and().formLogin()
                .permitAll()
                .and().csrf().disable();
        // 需要手动 build 生成过滤器链
        return http.build();
    }


}
